<?php
/**
 * brand.php
 *
 * Created on 2014-12-26
 * Create by LDD
 */
namespace haibao\cms\data;


class BrandImg extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\BrandImg');
	}

	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function add($model){
		parent::add($model);
		
		$this->updateBrandUpdateTime($model->BrandId);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->addOldBrandImg($model);
			if($oldId){
				$this->addDataMigrationMap($model,$oldId);
			}
			
		}
		return $model->Id;
	}
	/**
	 * @param \haibao\cms\model\filter\BrandImg $filter
	 */
	public  function getAll($filter){
		return parent::getAll($filter);
	}
	
	public function deleteBrandImg($id,$status){
		parent::updateById($id, array('Status'=>$status));
		
		$this->updateBrandUpdateTime($id);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->getDataMigration('BrandImg',$id);
			if($oldId){
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
				$sql ="delete from library_brand_pic where h_id= %s";
				$this->query($sql,array($oldId));
			}
		}
	}
	
	//TT addtime 2015.11.26
	//修改品牌库某品牌记录的修改日期
	private function updateBrandUpdateTime($brandId){
		$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where Id = %s";
		$this->query ($sql, array($brandId));
	}
	
	
	/**
	 * 添加老数据
	 */
	private function addOldBrandImg($model){
		$avatar = '';
		if($model->ImgId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$avatar = ltrim($imageData->getImageUrl($model->ImgId),"/");
		}
		$oldBrandId = $this->getDataMigration('Brand',$model->BrandId);
		if($oldBrandId){
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql = "insert into library_brand_pic (`h_brandid`,`h_inputtime`,`h_picname`,`h_status`)values(%s,%s,%s,%s)";
			$this->query($sql,array($oldBrandId,$model->CreateTime,$avatar,0));
			return $this->getDb()->insert_id;
		}
	}
	private function addDataMigrationMap($model,$oldId){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
	
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldId));
	}
	/**
	 *
	 * @param string $tableName
	 * @param int $newPrimaryKey
	 */
	private function getDataMigration($tableName,$newPrimaryKey){
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}
}
